// @ts-ignore
/* eslint-disable */
import md5 from 'md5';
import { Graphql } from '../utils';

const gqlGetUserList = `
query get_user_list($limit: Int = 10, $offset: Int = 0, $username: String, $mobile: String) {
  illuminant_user(order_by: {updated_at: desc}, limit: $limit, offset: $offset, where: {username: {_ilike: $username}, mobile: {_ilike: $mobile}}) {
    id
    username
    mobile
    email
    sex
    created_at
    updated_at
  }
  illuminant_user_aggregate(where: {username: {_ilike: $username}, mobile: {_ilike: $mobile}}) {
    aggregate {
      count
    }
  }
}`;

const gqlCreateUser = `mutation create_user($username: String!, $sex: Int = 1, $mobile: String!, $email: String = "", $password: String!) {
  insert_illuminant_user_one(object: {username: $username, sex: $sex, mobile: $mobile, email: $email, password: $password}) {
    id
  }
}`;

const gqlUpdateUser = `mutation update_user_by_pk($id: uuid!, $username: String, $sex: Int = 1, $mobile: String, $email: String) {
  update_illuminant_user_by_pk(pk_columns: {id: $id}, _set: {username: $username, sex: $sex, mobile: $mobile, email: $email}) {
    id
  }
}`;

const gqlDeleteUser = `mutation delete_user_by_pk($id: uuid!) {
  delete_illuminant_user_by_pk(id: $id) {
    id
  }
}`;

export async function getUserList(params: API.UserItem & API.PageInfo) {
  const gqlVar = {
    limit: params.pageSize ? params.pageSize : 10,
    offset: params.current && params.pageSize ? (params.current - 1) * params.pageSize : 0,
    mobile: params.mobile ? `%${params.mobile}%` : '%%',
    username: params.username ? `%${params.username}%` : '%%',
  };

  return Graphql<API.UserListResult>(gqlGetUserList, gqlVar);
}

export async function createUser(params: API.UserItem) {
  const gqlVar = {
    username: params.username,
    mobile: params.mobile,
    sex: params.sex,
    email: params.email ? params.email : '',
    password: md5('123456'),
  };

  return Graphql<API.CreateUserResult>(gqlCreateUser, gqlVar);
}

export async function updateUser(params: API.UserItem) {
  const gqlVar = {
    id: params.id,
    username: params.username,
    mobile: params.mobile,
    sex: params.sex,
    email: params.email ? params.email : '',
  };

  return Graphql<API.UpdateUserResult>(gqlUpdateUser, gqlVar);
}

export async function deleteUser(id: string) {
  return Graphql<API.DeleteUserResult>(gqlDeleteUser, { id });
}
